/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.manager.pipelineFactory;

import com.icee.myth.manager.ManagerKeyStore;
import com.icee.myth.manager.channelHandler.BootstrapToManagerHandler;
import com.icee.myth.manager.encoder.ManagerToBootstrapEncoder;
import java.security.KeyStore;
import java.security.Security;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import static org.jboss.netty.channel.Channels.*;
import javax.net.ssl.SSLEngine;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.ssl.SslHandler;

/**
 *
 * @author liuxianke
 */
public class BootstrapToManagerPipelineFactory implements ChannelPipelineFactory {

	@Override
    public ChannelPipeline getPipeline() throws Exception {
        ChannelPipeline pipeline = pipeline();

        String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
        if (algorithm == null) {
            algorithm = "SunX509";
        }

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ManagerKeyStore.asInputStream(),
                ManagerKeyStore.getKeyStorePassword());

        // Set up key manager factory to use our key store
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks, ManagerKeyStore.getCertificatePassword());

        // Initialize the SSLContext to work with our key managers.
        SSLContext serverContext = SSLContext.getInstance("TLS");
        serverContext.init(kmf.getKeyManagers(), null, null);

        SSLEngine engine = serverContext.createSSLEngine();
        engine.setUseClientMode(false);

        // Add SSL handler first to encrypt and decrypt everything.
        // In this example, we use a bogus certificate in the server side
        // and accept any invalid certificates in the client side.
        // You will need something more complicated to identify both
        // and server in the real world.
        //
        // Read SecureChatSslContextFactory
        // if you need client certificate authentication.
        pipeline.addLast("ssl", new SslHandler(engine));

        // On top of the SSL handler, add the codec.
        pipeline.addLast("encoder", new ManagerToBootstrapEncoder());

        // and then business logic.
        pipeline.addLast("handler", new BootstrapToManagerHandler());

        return pipeline;
    }
}
